//
//  expandNsData.m
//  EasyToTesco2.0
//
//  Created by 杨森 on 2017/3/24.
//  Copyright © 2017年 EasyToTesco. All rights reserved.
//

#import "ExpandSnPlist.h"
#import <objc/runtime.h>

@interface ExpandSnPlist()

@property(nonatomic,strong)NSString *fileName;

@property(nonatomic,strong)NSFileManager *filePath;

@property(nonatomic,strong)NSMutableArray *fileArray;

@end

@implementation ExpandSnPlist

+ (instancetype)shareExpandPlist
{
    static ExpandSnPlist *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[ExpandSnPlist alloc] init];
        [instance createPlist];
    });
    return instance;
}

- (void)createPlist {
    
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject];
    _fileName = [documentPath stringByAppendingPathComponent:@"expandSn.plist"];
    _filePath = [NSFileManager defaultManager];
    [_filePath createFileAtPath:_fileName contents:nil attributes:nil];
   
}

- (BOOL)isSnPlistFileExist
{
    if ([_filePath fileExistsAtPath:_fileName]) {
        NSArray *array =  [self readAllDataWithPath:_fileName];
        if (array.count > 0 ) {
            NSLog(@"expandSn exists");
            return true;
        }else{
            NSLog(@"expandSn not exists");
            return false;
        }
    }
    return nil;
}

- (void)writeToPlistWithKey:(NSString *)key value:(id)value {
    [self writeToPlistWithKey:key value:value path:_fileName];
}

- (void)writeToPlistWithDic:(NSDictionary *)dict {
    [self writeToPlistWithDic:dict path:_fileName];
}

//读取
- (id)readDataWithKey:(NSString *)key {
    return [self readDataWithKey:key path:_fileName];
}

- (id)readAllData {
    return [self readAllDataWithPath:_fileName];
}

- (void)removePlist {
    [self removePlistWithPath:_fileName];
}


- (void)writeToPlistWithKey:(NSString *)key
                      value:(id)value
                       path:(NSString *)path {
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
    if (dic == nil) {
        dic = [NSMutableDictionary dictionary];
    }
    [dic setObject:value forKey:key];
    [dic writeToFile:path atomically:YES ];
}

- (void)writeToPlistWithDic:(NSDictionary *)dic path:(NSString *)path {
    
    NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
    if (tempDict == nil) {
        tempDict = [NSMutableDictionary dictionary];
    }
 
    NSMutableDictionary *newDict = [[NSMutableDictionary alloc] initWithDictionary:dic];

    if (SN_IS_EXIST) {
        
        //最新的邀请码
        NSString *newPId = [dic objectForKey:SN_PRODUCT_ID];
        NSString *newSnId = [dic objectForKey:SN_EXPAND_ID];

        NSArray *snArray = [self readAllDataWithPath:_fileName];
        NSString *oldPId = nil;
        NSString *oldSnId = nil;
        
        for (NSDictionary *snDict in snArray) {
            oldPId = [snDict objectForKey:SN_PRODUCT_ID];
            oldSnId = [snDict objectForKey:SN_EXPAND_ID];
            //如果商品id相同
            if ([oldPId isEqualToString:newPId]) {
                
                //邀请码相同 不加
                if ([newSnId isEqualToString:oldSnId]) {
                    return;
                }else{
                //邀请码不同 覆盖
                    [self.fileArray removeObject:snDict];
                }
                
            }else{//商品id不同
                //邀请码相同  添加
                if ([newSnId isEqualToString:oldPId]) {
                    break;
                }else{
                //邀请码不同  添加
                    break;
                }
            }
        }

    }
    
    
    
    [tempDict addEntriesFromDictionary:newDict];
    [self.fileArray addObject:tempDict];
    BOOL stutas = [self.fileArray writeToFile:_fileName atomically:YES];
    if (stutas) {
        NSLog(@"sn写入成功");
    } else {
        NSLog(@"sn写入失败");
    }
    NSLog(@"%@",_fileName);

}

//读取
- (id)readDataWithKey:(NSString *)key
                 path:(NSString *)path {
    NSData *plistData = [NSData dataWithContentsOfFile:path];
    
    NSString *plistError;
    NSPropertyListFormat format;
    
    if (plistData) {
        if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
            id plist = [NSPropertyListSerialization propertyListFromData:plistData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&plistError];
            return [(NSArray *)plist valueForKey:key];
#pragma clang diagnostic pop
        } else {
            NSError *error = nil;
            id plist = [NSPropertyListSerialization propertyListWithData:plistData options:NSPropertyListReadCorruptError format:&format error:&error];
            return [(NSArray *)plist valueForKey:key];
        }
    } else {
        return nil;
    }
}

- (id)readAllDataWithPath:(NSString *)path {
    NSData *plistData = [NSData dataWithContentsOfFile:path];
    
    NSString *plistError;
    NSPropertyListFormat format;
    
    if (plistData) {
        
        if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
            id plist = [NSPropertyListSerialization propertyListFromData:plistData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&plistError];
            return (NSDictionary *)plist;
#pragma clang diagnostic pop
        } else {
            NSError *error = nil;
            id plist = [NSPropertyListSerialization propertyListWithData:plistData options:NSPropertyListReadCorruptError format:&format error:&error];
            return (NSDictionary *)plist;
        }
        
    } else {
        return nil;
    }
}

- (void)removePlistWithPath:(NSString *)path {
    NSFileManager *manager = [NSFileManager defaultManager];
    [manager removeItemAtPath:path error:nil];
}

- (NSMutableArray *)fileArray
{
    if (!_fileArray) {
        _fileArray = [NSMutableArray array];
    }
    return _fileArray;
}

@end
